<template>
  <view class="container">
    <!-- 导航栏（保留初始） -->
    <uni-nav-bar 
      dark 
      :fixed="true" 
      shadow 
      status-bar 
      left-icon="arrow-left" 
      title="维护设置" 
      @clickLeft="back" 
    />

    <!-- 加载中 -->
    <uni-load-more v-if="loading" status="loading" content-text="正在加载..." />

    <!-- 数据加载完成后显示的内容 -->
    <view v-else>
      <!-- 九宫格：渲染所有后端数据 -->
      <view class="grid-container">
        <view 
          v-for="(item, index) in displayedList" 
          :key="item.id"
          class="grid-item"
          @click="handleGridItemClick(item)" 
          :class="{ 'clickable': item.dz }" 
        >
          <!-- 图标：用后端tb -->
          <view class="icon-wrapper">
            <image 
              :src="item.tb" 
              mode="widthFix" 
              class="grid-img"
              @error="handleImgError(item)"
            ></image>
            <!-- 新标签：用后端isnew -->
            <view class="new-tag" v-if="item.isnew === '1'">新</view>
          </view>

          <!-- 文字：用后端name -->
          <text class="grid-text">
            {{ item.name || '待配置' }}
          </text>
        </view>
      </view>

      <!-- 独立的退出登录按钮 -->
      <view class="logout-btn" @click="handleLogout">
        <view class="icon-wrapper">
          <image 
            src="/static/bk-ico/logout.png" 
            mode="widthFix" 
            class="logout-img"
          ></image>
        </view>
        <text class="logout-text">重新登录</text>
      </view>
    </view>

    <view class="remaining-area"></view>
  </view>
</template>

<script>
import store from '../../common/store.js'
import utils from '../../common/utils'

export default {
  data() {
    return {
      loading: true,
      tqfkbBkList: [], // 后端数据
      displayedList: [] // 用于展示的列表（补全后）
    }
  },
  onLoad() {
    this.initPage()
  },
  methods: {
    // 初始化页面，加载数据并补全九宫格
    initPage: async function () {
      this.$utils.showLoading("数据加载中...");
      try {
        const timestamp = this.$utils.getTimestamp();
        const userInfo = uni.getStorageSync("userInfo");
        const enData = this.$utils.encrypt(
          JSON.stringify({ timestamp }),
          userInfo.aesKey,
          userInfo.aesIv
        );
        const res = await this.$myRequest.post_token(
          getApp().globalData.qtwhInit,
          { data: enData + "" }
        );
        
        this.$utils.hideLoading();
        if (res.code === 200) {
          const a = JSON.parse(utils.decrypt(
            res.data,
            userInfo.aesKey,
            userInfo.aesIv
          ));
          this.tqfkbBkList = a.TqfkbBkList || [];
          // 补全九宫格到9个
          this.completeGridList();
        } else {
          this.$utils.toast(`数据加载失败！错误码[${res.code}]`);
          // 加载失败也补全九宫格
          this.completeGridList();
        }
      } catch (e) {  
        this.$utils.hideLoading();
        console.error("数据加载异常：", e);
        this.$utils.toast("数据加载失败！" + e.message);
        // 异常时也补全九宫格
        this.completeGridList();
      } finally {
        this.loading = false;
      }
    },

    // 补全九宫格到9个项目
    completeGridList() {
      this.displayedList = [...this.tqfkbBkList];
      const defaultIcon = '/static/bk-ico/kb.png';
      
      // 计算需要补充的数量
      const needToAdd = 9 - this.displayedList.length;
      
      // 补充默认项目
      for (let i = 0; i < needToAdd; i++) {
        this.displayedList.push({
          id: `default-${i}`,
          name: ``,
          tb: defaultIcon,
          isnew: '0',
          // 默认项不添加dz属性，点击不跳转
        });
      }
    },

    // 处理图片加载失败
    handleImgError(item) {
      item.tb = '/static/bk-ico/default.png';
    },

    // 返回上一页
    back() {
      uni.switchTab({
        url: '/pages/index/index',
        fail: (err) => {
          uni.redirectTo({
            url: '/pages/index/index',
            fail: (err2) => {
              console.error('跳转首页失败：', err2);
              uni.navigateBack();
            }
          });
        }
      });
    },

    // 处理退出登录
    handleLogout() {
      store.clearLoginInfo()
      uni.reLaunch({ url: '/pages/login/login' })
      uni.showToast({ title: '已退出登录', icon: 'none' })
    },

    // 处理九宫格项点击事件
    handleGridItemClick(item) {
      // 检查是否有有效的跳转路径
      if (item.dz) {
        // 使用uni.navigateTo进行页面跳转
        uni.navigateTo({
          url: item.dz,
          fail: (err) => {
            console.error('页面跳转失败：', err);
            this.$utils.toast('页面跳转失败，请稍后重试');
          }
        });
      } else if (!item.name) {
        // 对于没有名称和链接的默认项，点击给出提示
        this.$utils.toast('功能待配置');
      }
    }
  }
}
</script>

<style scoped>
/* 完全保留你最初的样式 */
.container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 0rpx 30rpx 30rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.uni-load-more {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.grid-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  width: 100%;
  gap: 20rpx;
  margin-bottom: 30rpx;
  padding-top: 20rpx;
}

.grid-item {
  width: calc(33.33% - 14rpx);
  height: 220rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  position: relative;
}

/* 可点击项的样式 */
.grid-item.clickable {
  cursor: pointer;
}

.grid-item.clickable:active {
  transform: scale(0.95);
  opacity: 0.8;
}

.icon-wrapper {
  position: relative;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.grid-img {
  width: 60rpx;
  height: 60rpx;
  object-fit: contain;
}

.new-tag {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background-color: #ff4d4f;
  color: #fff;
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  border-radius: 12rpx;
  z-index: 1;
}

.grid-text {
  margin-top: 16rpx;
  font-size: 28rpx;
  color: #333;
  text-align: center;
  padding: 0 8rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 退出登录按钮样式 */
.logout-btn {
  width: 100%;
  height: 100rpx;
  background-color: #ff4d4f;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20rpx;
}

.logout-img {
  width: 40rpx;
  height: 40rpx;
  margin-right: 16rpx;
  object-fit: contain;
}

.logout-text {
  font-size: 32rpx;
  color: #fff;
}

.remaining-area {
  flex: 1;
}
</style>
